<template>
  <view class="form-content">
    <view class="title" v-if="showFormTitle"> 
      <view class="form-title">{{ formTitle }}</view>
      <slot v-if="showButton" name="buttonName"></slot> 
    </view>
    <uni-forms ref="formRef" :modelValue="ruleForm">
      <view v-for="(item, index) in allFormConfig" :key="index" v-show="!item.hiddenItem">
        <uni-forms-item :name="item.key">
          <view slot="label" :class="[topTypes.includes(item.type) || item.isTopLabel ? 'top-label' : 'left-label']">
            <text class="required-mark" v-if="getRequired(item)">*</text>
            <slot v-if="item.isLabelSlot" :name="item.labelSlot"></slot>
            <view v-else>
              {{ item.label }}
              <view v-if="item.labelDesc" class="label-desc">({{ item.labelDesc }})</view>
            </view>
          </view>
          <!-- input输入框 -->
          <view v-if="item.type==='input'" class="input-content">
            <slot v-if="item.prefixSlot" :name="item.prefixName"></slot>
            <uni-easyinput
              :ref="`${item.key}Input`"
              v-model="ruleForm[item.key]"
              :placeholder="item.suffixSlot?'':item.placeholder || `请输入${item.label}`"
              :disabled="item.isDisabled || false"
              :maxlength="item.maxLength"
              @blur="inputBlur($event, item)"
            ></uni-easyinput>
            <slot v-if="item.suffixSlot" :name="item.suffixName"></slot>
            <view v-if="item.suffixText" class="suffix-text" style="background:none">{{ item.suffixText }}</view>
          </view>
          <!-- select选择框 -->
          <uni-data-select
            class="you-select"
            v-if="item.type==='select'"
            v-model="ruleForm[item.key]"
            :localdata="optionsObj[item.key]"
            :placeholder="item.placeholder || `请选择${item.label}`"
            :disabled="item.isDisabled || false"
            @change="selectChange($event, item)"
          ></uni-data-select>
          <!-- password框 -->
          <uni-easyinput
            v-if="item.type==='password'"
            :ref="`${item.key}Input`"
            type="password"
            v-model="ruleForm[item.key]"
            :maxlength="item.maxLength"
            :disabled="item.isDisabled || false"
            :placeholder="item.placeholder || `请输入${item.label}`"
            @blur="inputBlur($event, item)"
          />
          <!-- 文本框 -->
          <uni-easyinput
            v-if="item.type==='textarea'"
            :ref="`${item.key}Input`"
            type="textarea"
            v-model="ruleForm[item.key]"
            :maxlength="item.maxLength"
            :disabled="item.isDisabled || false"
            :placeholder="item.placeholder || `请输入${item.label}`"
            @blur="inputBlur($event, item)"
          />
          <!-- 多选框 -->
          <multiple-select
            class="you-select"
            v-if="item.type==='multipleSelect'"
            :multiple="item.multiple"
            :filterable="item.filterable"
            v-model="ruleForm[item.key]"
            :localData="optionsObj[item.key]"
            :placeholder="item.placeholder || `请选择${item.label}`"
            :disabled="item.isDisabled || false"
            @change="multipleSelectChange($event, item)"
            @inputChange="multipleInputChange($event, item)"
          ></multiple-select>
          <!-- 树形选择框 -->
          <view v-if="item.type==='treeSelect'" @click="clickTreeSelect(item.key)" class="tree-item">
            <view v-if="treeSelectForm[item.key] && treeSelectForm[item.key].length">
              <view v-for="(tItem, tIndex) in treeSelectForm[item.key]" :key="tIndex">
                {{ tItem[item.props.label || 'name'] }}
                <text v-if="tIndex !== treeSelectForm[item.key].length - 1">,</text>
              </view>
            </view>
            <view v-else class="placeholder">{{ `请选择${item.label}` }}</view>
            <uni-icons v-if="!ruleForm[item.key]" class="tree-icon" type="right" size="14" color="rgba(106, 106, 106, .7)"></uni-icons>
            <tree-select-drawer
              :ref="`${item.key}TreeSelect`"
              :value="treeSelectForm[item.key]"
              :ruleFormData="ruleForm[item.key]"
              :treeData="item.options"
              :props="item.props"
              @confirm="clickConfirmTree($event, item)"
            ></tree-select-drawer>
          </view>
          <!-- 时间选择器 -->
          <uni-datetime-picker
            v-model="ruleForm[item.key]"
            v-if="item.type==='dateTime'"
            :type="item.dateType || 'datetime'"
            :return-type="item.returnType || 'string'"
            :disabled="item.isDisabled || false"
            :start="item.minDate"
            @change="dateTimeChange($event, item)"
          />
          <!-- 级联选择器 -->
          <picker-form
            v-if="item.type==='picker'"
            class="picker-content"
            :pickerForm="pickerFormData"
            :item="item"
            :localData="optionsObj"
            @setPickerForm="setPickerForm"
          >
            <template v-slot:right v-if="item.rightSlot">
              <slot :name="item.rightSlotName"></slot>
            </template>
          </picker-form>
          <!-- 单选框 -->
          <uni-data-checkbox
            class="radio-box"
            v-if="item.type==='radioGroup'"
            v-model="ruleForm[item.key]"
            :localdata="item.options"
            selectedColor="#115BAA"
            :disabled="item.isDisabled || false"
            @change="radioChange($event, item)"
          ></uni-data-checkbox>
          <!-- 多选框 -->
          <uni-data-checkbox
            class="check-box"
            v-if="item.type==='checkbox'"
            :multiple="true"
            v-model="ruleForm[item.key]"
            :localdata="item.options"
            selectedColor="#115BAA"
            :disabled="item.isDisabled || false"
          ></uni-data-checkbox>
          <!-- 有弹窗的多选框 -->
          <check-group
            v-if="item.type==='checkboxGroup'"
            :item="item"
            :ruleForm="ruleForm"
            @setRuleForm="setRuleForm"
          ></check-group>
          <!-- switch选择 -->
          <switch
            color="#115BAA"
            style="transform: scale(0.7)"
            v-if="item.type==='switch'"
            :value="ruleForm[item.key]"
            :checked="item.initVal === item.activeValue || item.initVal === true"
            :disabled="item.isDisabled || false"
            @change="onSwitchChange($event, item)"
          ></switch>
          <!-- 图片上传 -->
          <uni-file-picker
            v-if="item.type==='imgUpload'"
            v-model="fileForm[item.key]"
            :limit="item.limit || 10"
            :imageStyles="imageStyles"
            :disabled="item.isDisabled || false"
            :del-icon="!item.isDisabled"
            @delete="clickDelete($event, item.key)"
            @select="uploadSelect($event, item, item.limit === 1)"
          >
            <uni-icons type="camera-filled" size="30" color="#999999"></uni-icons>
            <view class="desc">{{ item.desc || '点击上传' }}</view>
          </uni-file-picker>
          <!-- 图片组上传 -->
          <view v-if="item.type==='imgGroupUpload'" class="img-group">
            <view class="picker-item" v-for="(iItem, iIndex) in item.imgGroupList" :key="iIndex">
              <uni-file-picker
                v-model="fileForm[iItem.key]"
                :limit="1"
                :imageStyles="imageStyles"
                :disabled="item.isDisabled || iItem.isDisabled || false"
                :del-icon="!item.isDisabled && !iItem.isDisable"
                @delete="clickDelete($event, iItem.key)"
                @select="uploadSelect($event, iItem, true)"
              >
                <uni-icons type="camera-filled" size="30" color="#999999"></uni-icons>
                <view class="desc">{{ iItem.desc }}</view>
              </uni-file-picker>
              <view class="example-box" v-if="iItem.exampleImg" @click="clickExample(item, iItem)">示例图</view>
            </view>
          </view>
          <!-- 课程上传 -->
          <view v-if="item.type==='videoUpload'" class="video-upload">
            <view v-if="showFile[item.key]">
              <video style="border-radius: 32rpx;height: 240rpx;" :src="fileForm[item.key][0].url" />
            </view>
            <uni-file-picker
              v-model="fileForm[item.key]"
              :limit="item.limit || 10"
              :disabled="item.isDisabled || false"
              file-mediatype="video"
              :file-extname="item.fileType || 'mp4,mov,avi'"
              return-type="object"
              :del-icon="!item.isDisabled"
              @select="uploadSelect($event, item, item.limit === 1)"
            >
              <view class="video-box">
                <uni-icons type="videocam-filled" size="26" color="#999999"></uni-icons>
              </view>
            </uni-file-picker>
          </view>
          <!-- 音频上传 -->
          <view v-if="item.type==='audioUpload'" class="video-upload">
            <view v-if="showFile[item.key]">
              <view class="audio-item" v-for="(fItem, fIndex) in fileFormData[item.key]" :key="fIndex">
                <view class="left-box">
                  <image class="img" :src="baseIconUrl + '/commonIcon/icon_audio_bg.png'" mode="aspectFill"/>
                  <view class="icon-box" @click="clickPlayAudio(fItem.url, item.key, fIndex)">
                    <image v-if="!playConfig[item.key].opened[fIndex]" class="btn-img" :src="baseIconUrl + '/commonIcon/icon_play_btn.png'" mode="aspectFill"/>
                    <image v-else class="btn-img" :src="baseIconUrl + '/commonIcon/icon_stop_btn.png'" mode="aspectFill"/>
                  </view>
                </view>
                <view class="content-box">{{ fItem.name }}</view>
                <view class="right-box" @click="clickDeleteAudio(fItem, item.key)">×</view>
              </view>
            </view>
            <uni-file-picker
              v-model="fileFormData[item.key]"
              :limit="item.limit || 10"
              :disabled="item.isDisabled || false"
              file-mediatype="all"
              :del-icon="!item.isDisabled"
              :file-extname="item.fileType || 'mp3,wav'"
              @select="uploadSelect($event, item, item.limit === 1)"
            >
              <view class="audio-box">
                <uni-icons type="sound-filled" size="30" color="#999999"></uni-icons>
              </view>
            </uni-file-picker>
          </view>
          <!-- 文件上传 -->
          <view v-if="item.type==='fileUpload'" class="file-upload">
            <uni-file-picker
              v-model="fileFormData[item.key]"
              :limit="item.limit || 10"
              :disabled="item.isDisabled || false"
              file-mediatype="all"
              :del-icon="!item.isDisabled"
              :file-extname="item.fileType || 'docx,xls,xlsx,ppt,txt,pdf'"
              @delete="clickDelete($event, item.key)"
              @select="uploadSelect($event, item, item.limit === 1)"
            >
              <view class="file-box">
                <uni-icons type="upload-filled" size="26" color="#1e89ff"></uni-icons>
              </view>
            </uni-file-picker>
          </view>
          <view v-if="item.type==='selectInput'" class="select-input">
            <uni-data-select
              v-model="ruleForm[item.selectKey]"
              :localdata="item.options"
              :placeholder="item.selectPlaceholder"
              :disabled="item.isDisabled || false"
              @change="selectChange($event, item)"
            ></uni-data-select>
            <uni-easyinput
              v-model="ruleForm[item.inputKey]"
              :placeholder="item.inputPlaceholder"
              :disabled="item.isDisabled || false"
            ></uni-easyinput>
          </view>
          <slot
            v-if="item.type === 'slot' || item.type === 'topSlot'"
            :name="item.slotName"
          ></slot>
          <slot v-if="item.isRightSlot" :name="item.rightSlot">
            <view class="item-right-slot">{{ item.rightSlotText || '' }}</view>
          </slot>
        </uni-forms-item>
        <slot v-if="item.isContentSlot" :name="item.contentSlot">
        </slot>
      </view>
    </uni-forms>
    <you-popup
      :popupVisible="exampleDialog"
      popupTitle="示例图"
      :showBtn="false"
	    @popupClose="exampleDialog = false"
    >
      <template #popupContent>
        <image class="example-img" :src="exampleImgUrl" />
      </template>
    </you-popup>
  </view>
</template>

<script>
  import api_select from '@/api/select'
  import api_remoteQuery from '@/api/remoteQuery'
  import { getToken } from "@/utils/auth"
  import { baseUrl, baseIconUrl } from '@/config'
  import PickerForm from './components/pickerForm'
  import MultipleSelect from './components/multipleSelect'
  import CheckGroup from './components/checkGroup'
  import TreeSelectDrawer from './components/treeSelectDrawer.vue'
  import customValidate from '@/utils/customValidate'
  export default {
    name: 'form',
    components: { PickerForm, MultipleSelect, CheckGroup, TreeSelectDrawer },
    data() {
      return {
        baseUrl,
        baseIconUrl,
        rules: {},
        allFormConfig: [],
        imageStyles: {
          width: 100,
					height: 100,
          border: {
            color: "#D8DCE5",
            width: '2rpx',
            style: 'dashed',
            radius: '16rpx'
          }
        },
        ruleForm: {},
        fileForm: {},
        fileFormData: {},
        pickerForm: {},
        pickerFormData: {},
        showFile: {},
        isShowFile: false,
        optionsObj: {}, // 所有数据的options数据
        selectOptionsData: {},
        topTypes: [
          'textarea',
          'imgUpload',
          'imgGroupUpload',
          'videoUpload',
          'audioUpload',
          'fileUpload',
          'checkbox',
          'topSlot',
          'selectInput'
        ], // label在上方的表单
        selectNames: '',
        treeSelectForm: {},
        playConfig: {},
        innerAudioConfig: {},
        exampleImgUrl: ''
      }
    },
    props: {
      formTitle: {
        type: String,
        default: '表单标题'
      },
      formConfig: {
        type: Array,
        default: []
      },
      value: {
        type: Object,
        default: {}
      },
      showFormTitle: {
        type: Boolean,
        default: true
      },
      showButton: {
        type: Boolean,
        default: false
      },
      customValName: {
        type: String,
        default: ''
      }
    },
    watch: {
      formConfig: {
        handler(newVal, oldVal) {
          const formConfig = uni.$u.deepClone(newVal)
          formConfig.forEach(item => {
            this.selectOptions(item)
            if (item.type === 'audioUpload') {
              this.playConfig[item.key] = {
                opened: [],
                url: []
              }
              this.innerAudioConfig[item.key] = []
            }
          })
          this.allFormConfig = formConfig
          this.getRules()
        },
        deep: true,
        immediate: true
      },
      ruleForm: {
        handler(newVal, oldVal) {
          if (!newVal) return
          this.formConfig.forEach(item => {
            if (item.type === 'treeSelect' && newVal[item.key]) {
              this.getTreeInitData([newVal[item.key]], item.options, item)
            }
            if (item.type === 'picker' && newVal[item.key]) {
              this.pickerFormData[item.key] = newVal[item.key]
            }
          })
          this.$emit('input', newVal)
        },
        deep: true
      }
    },
    onReady() {
      this.ruleForm = { ...this.value }
      this.getInitVal()
      this.getRules(true)
    },
    methods: {
      getTreeInitData(data, options, item) {
        const itemForm = this.treeSelectForm[item.key] || []
        const itemValue = itemForm.map(iItem => iItem[item.props.value || 'id'])
				options.forEach(oItem => {
          const value = oItem[item.props.value] || 'id'
          if ((data.includes(value) || data == value) && !itemValue.includes(value)) {
            itemForm.push({
              [item.props.label || 'name']: oItem[item.props.label || 'name'],
              [item.props.value || 'id']: oItem[item.props.value || 'id']
            })
            this.treeSelectForm = {
              ...this.treeSelectForm,
              [item.key]: itemForm
            }
					}
					if (oItem.children && oItem.children.length) {
						this.getTreeInitData(data, oItem.children, item)
					}
				})
			},
      setRuleForm(ruleForm) {
        this.ruleForm = ruleForm
      },
      getInitVal() {
        this.formConfig.forEach(item => {
          const commonType = ['imgUpload', 'videoUpload', 'audioUpload', 'fileUpload']
          if (commonType.includes(item.type) && this.ruleForm[item.key]) {
            const dataList = this.ruleForm[item.key].split(',')
            this.fileForm[item.key] = dataList.map((item, index) => {
              return {
                url: item.includes('http') ? item : this.baseUrl + item,
                fileId: index
              }
            })
            this.showFile[item.key] = true
          }
          if (item.type === 'imgGroupUpload') {
            item.imgGroupList.forEach((iItem, iIndex) => {
              if (this.ruleForm[iItem.key]) {
                this.fileForm[iItem.key] = {
                  url: this.ruleForm[iItem.key].includes('http') ? this.ruleForm[iItem.key] : this.baseUrl + this.ruleForm[iItem.key],
                  fileId: iIndex
                }
                this.showFile[iItem.key] = true
              }
            })
          }
          if (this.ruleForm[item.key] !== null && this.ruleForm[item.key] !== undefined) {
            return
          } else {
            if (item.type === 'checkbox') {
              this.ruleForm[item.key] = []
            }
          }
          if (item.initVal !== null && item.initVal !== undefined) {
            this.ruleForm[item.key] = item.initVal
          }
        })
      },
      // 获取校验规则
      getRules(needCustom) {
        this.formConfig.forEach(item => {
          const customValName = this.customValName
          this.rules[item.key] = {}
          if (item.hiddenItem) return
          let itemRules = item.rules
          if (needCustom && customValidate[customValName] && customValidate[customValName][item.key]) {
            customValidate[customValName][item.key].forEach(cItem => {
              if (!itemRules) itemRules = []
              itemRules.push({
                validateFunction: cItem
              })
            })
          }
          if (item.type === 'imgGroupUpload' || item.type === 'slot') {
            return
          } else {
            this.rules[item.key]['rules'] = itemRules
          }
        })
        this.$nextTick(() => {
          if (this.$refs.formRef) {
            this.$refs.formRef.setRules(this.rules)
          }
        })
      },
      getRequired(item) {
        if (!item.rules) return false
        const required = item.rules.filter(item => item.required)
        return required.length
      },
      inputBlur($event, item) {
        this.$emit("inputBlur", { item, $event })
      },
      // 下拉框更改
      selectChange($event, item) {
        if (item.labelKey) {
          this.ruleForm[item.labelKey] = ''
          this.getSelectLabel($event, item)
        }
        if (item.selectKey) {
          this.$emit(item.selectKey+ 'Change', $event, item)
        } else {
          this.$emit(item.key + 'Change', $event)
        }
      },
      // 多选框下拉更改
      multipleSelectChange($event, item) {
        if (item.selectKey) {
          this.$emit(item.selectKey+ 'Change', this.ruleForm[item.key], item)
        } else {
          this.$emit(item.key + 'Change', this.ruleForm[item.key])
        }
        if (!($event && $event.length)) return
        this.ruleForm[item.key] = $event.map(item => item.value)
        if (item.urlOptions) {
          item.urlOptions.params = {}
        }
      },
      // 树形数据切换
      treeSelectChange(val, item) {
        this.$emit(item.key + 'TreeChange', val, item)
      },
      // 多选框输入更改
      async multipleInputChange($event, item) {
        this.remoteMethod($event, item)
      },
      // 远程搜索数据
      remoteMethod(query, item) {
        const params = {
          [item.remoteConfig.paramsName]: query
        }
        api_remoteQuery[item.remoteConfig.queryName](params).then(res => {
          if (item.remoteConfig.dataLocal) {
            const options = this.getOptionsConfig(res[item.remoteConfig.dataLocal], item, 'remoteConfig')
            this.optionsObj = {
              ...this.optionsObj,
              [item.key]: options
            }
          } else {
            const options = this.getOptionsConfig(res.data, item, 'remoteConfig')
            this.optionsObj = {
              ...this.optionsObj,
              [item.key]: options
            }
          }
        })
      },
      getOptionsConfig(data, dItem, keyLocal) {
        let resultData = []
        data.forEach(item => {
          if (item.children) {
            resultData.push({
              text: item[dItem[keyLocal].keys.text],
              value: item[dItem[keyLocal].keys.value],
              children: this.getOptionsConfig(item.children, dItem, keyLocal)
            })
          } else {
            resultData.push({ text: item[dItem[keyLocal].keys.text], value: item[dItem[keyLocal].keys.value] })
          }
        })
        return resultData
      },
      // switch切换
      onSwitchChange($event, item) {
        let checkValue = $event.detail.value
        if (item.activeValue && item.inactiveValue) {
          checkValue = checkValue ? item.activeValue : item.inactiveValue
        }
        this.ruleForm[item.key] = checkValue
        this.$emit(item.key + 'SwitchChange', checkValue)
      },
      radioChange($event, item) {
        this.$emit(item.key + 'RadioChange', $event.detail.value)
      },
      // 文件类型数据处理
      getCustomData(formList) {
        let dataForm = {}
        formList.forEach(item => {
          const formName = item.name
          const dataKey = item.key
          for (let key in this[formName]) {
            if (!this[formName][key]) return
            if (formName === 'fileForm') {
              dataForm[key] = this[formName][key].map(fItem => fItem[dataKey]).join(item.splitIcon)
            } else if (this[formName][key][dataKey] instanceof Array) {
              const newData = this[formName][key][dataKey].filter(item => item !== 'empty' && item !== '')
              if (newData.length <= 1) {
                dataForm[key] = ''
              } else {
                dataForm[key] = this[formName][key][dataKey].join(item.splitIcon)
              }
            } else {
              dataForm[key] = this[formName][key][dataKey]
              const valueKey = this[formName][key]['valueKey']
              const labelKey = this[formName][key]['labelKey']
              if (valueKey) {
                dataForm[valueKey] = this[formName][key][valueKey].split('/')
              }
              if (labelKey) {
                dataForm[labelKey] = this[formName][key][labelKey].split('/')
              }
            }
          }
        })
        for (let key in dataForm) {
          this.ruleForm[key] = dataForm[key]
        }
      },
      // 表单校验
      async checkFormData() {
        uni.showLoading()
        await this.getRules(true)
        return this.$refs.formRef.validate().then(valid => {
          uni.hideLoading()
          return true
        }).catch(err => {
          uni.hideLoading()
          return false
        })
      },
      // 文件类型上传
      uploadSelect($event, item, onlyOne) {
        const key = item.key
        this.showFile[key] = false
        this.isShowFile = false
        const tempFilePaths = $event.tempFilePaths
        const tempFiles = $event.tempFiles[0]
        uni.uploadFile({
          url: this.baseUrl + '/common/upload',
          // H5上传
					// file: tempFilePaths,
					// 微信小程序上传
					filePath: tempFilePaths[0],
          name: 'file',
          header: {
            "Authorization": 'Bearer ' + getToken()
          },
          // 成功函数
          success: (res) => {
            // 取到文档服务器的值
            let uploadData = JSON.parse(res.data)
            this.$emit('success', uploadData, item.key)
            const fileForm = {}
            fileForm[key] = this.fileFormData[key] || []
            if (onlyOne) {
              fileForm[key] = [{
                url: uploadData.url,
                fileId: fileForm[key].length,
                originalFilename: uploadData.originalFilename,
                name: tempFiles.name,
                extname: tempFiles.extname
              }]
            } else {
              fileForm[key].push({
                url: uploadData.url,
                fileId: fileForm[key].length,
                originalFilename: uploadData.originalFilename,
                name: tempFiles.name,
                extname: tempFiles.extname
              })
            }
            this.fileFormData[key] = uni.$u.deepClone(fileForm[key])
            this.fileForm[key] = uni.$u.deepClone(fileForm[key])
            this.fileFormData[key].forEach(fItem => {
              if (this.playConfig[key]) {
                this.playConfig[key].opened.push(false)
                this.playConfig[key].url.push(fItem.url)
              }
            })
            const needForm = [
              { name: 'fileForm', key: 'url', splitIcon: ',' }
            ]
            this.getCustomData(needForm)
            this.showFile[key] = true
            this.isShowFile = true
          },
          // 失败提示用户重新上传
          fail: error => {
            console.log('失败', error)
          }
        })
      },
      // 音频手动播放
      clickPlayAudio(url, key, fIndex) {
        let that = this
        // 创建音频实例
        that.innerAudioConfig[key][fIndex] = that.innerAudioConfig[key][fIndex] || uni.createInnerAudioContext()
        // 音频地址
        that.innerAudioConfig[key][fIndex].src = url
        const playConfig = uni.$u.deepClone(that.playConfig)
        for (let pKey in playConfig) {
          if (pKey !== key) {
            playConfig[pKey].opened = playConfig[pKey].opened.map(oItem => false)
            playConfig[pKey].url.forEach((uItem, uIndex) => {
              that.innerAudioConfig[pKey][uIndex] = that.innerAudioConfig[pKey][uIndex] || uni.createInnerAudioContext()
              that.innerAudioConfig[pKey][uIndex].src = uItem
              that.innerAudioConfig[pKey][uIndex].pause()
            })
          } else {
            if (playConfig[key].opened[fIndex]) {
              that.innerAudioConfig[key][fIndex].pause()
              playConfig[key].opened[fIndex] = false
            } else {
              that.innerAudioConfig[key][fIndex].play()
              playConfig[key].opened[fIndex] = true
            }
          }
        }
        that.playConfig = uni.$u.deepClone(playConfig)
      },
      // 下拉框文字数据
      getSelectLabel(val, item) {
        item.options.forEach(oItem => {
          if (val === oItem.value) {
            this.ruleForm[item.labelKey] = oItem.text
          }
        })
      },
      // 点击树形框
      clickTreeSelect(key) {
        this.$refs[`${key}TreeSelect`][0].open()
      },
      // 树形确认
      clickConfirmTree($event, item) {
        const { selectIds, selectNames, selectList } = $event
        this.ruleForm = {
          ...this.ruleForm,
          [item.key]: selectIds
        }
        if (!selectIds) {
          this.treeSelectForm = {
            ...this.treeSelectForm,
            [item.key]: []
          }
        }
        this.$emit(item.key + 'TreeChange', this.ruleForm[item.key], item)
      },
      dateTimeChange($event, item) {
      },
      clickDelete($event, key) {
        this.fileForm[key] = this.fileForm[key].filter(item => item.url !== $event.tempFilePath)
        if (this.fileFormData[key] && this.fileFormData[key].length) {
          this.fileFormData = {
            ...this.fileFormData,
            [key]: this.fileFormData[key].filter(item => item.url !== $event.tempFilePath)
          }
        }
      },
      clickDeleteAudio(fItem, key) {
        this.fileForm[key] = this.fileForm[key].filter(item => item.url !== fItem.url)
        if (this.fileFormData[key] && this.fileFormData[key].length) {
          this.fileFormData = {
            ...this.fileFormData,
            [key]: this.fileFormData[key].filter(item => item.url !== fItem.url)
          }
        }
      },
      // 配置级联数据
      setPickerForm(pickerForm) {
        this.pickerForm = pickerForm
        const needForm = [
          { name: 'pickerForm', key: 'value', splitIcon: '-' }
        ]
        this.getCustomData(needForm)
      },
      selectOptions(item) {
        if (item.urlOptions && !(item.options && item.options.length)) {
          if (this.selectOptionsData[item.key]) return
          this.getUrlOptions(item)
        }
        if (item.options && item.options.length) {
          item.options = item.options
          this.optionsObj = {
            ...this.optionsObj,
            [item.key]: item.options
          }
          if (item.labelKey && item.type === 'select') {
            const value = this.ruleForm[item.key]
            this.getSelectLabel(value, item)
          }
        }
      },
      getUrlOptions(item) {
        const params = item.urlOptions.params
        this.selectOptionsData[item.key] = true
        api_select[item.urlOptions.requestName](params).then(res => {
          if (item.urlOptions.dataLocal) {
            if (!res[item.urlOptions.dataLocal] || res[item.urlOptions.dataLocal].length === 0) return
            const options = this.getOptionsConfig(res[item.urlOptions.dataLocal], item, 'urlOptions')
            item.options = options
            this.optionsObj = {
              ...this.optionsObj,
              [item.key]: item.options
            }
          } else {
            if (!res.rows || res.rows.length === 0) return
            const options = this.getOptionsConfig(res.rows, item, 'urlOptions')
            item.options = options
            this.optionsObj = {
              ...this.optionsObj,
              [item.key]: item.options
            }
          }
          if (item.labelKey && item.type === 'select') {
            const value = this.ruleForm[item.key]
            this.getSelectLabel(value, item)
          }
        }).catch(err => {
          this.selectOptionsData[item.key] = false
        })
      },
      getOptionsConfig(data, dItem, keyLocal) {
        let resultData = []
        data.forEach(item => {
          if (item.children) {
            resultData.push({
              text: item[dItem[keyLocal].keys.text],
              value: item[dItem[keyLocal].keys.value],
              children: this.getOptionsConfig(item.children, dItem, keyLocal) || null
            })
          } else {
            resultData.push({ text: item[dItem[keyLocal].keys.text], value: item[dItem[keyLocal].keys.value] })
          }
        })
        return resultData
      },
      clickExample(item, iItem) {
        const imgList = item.imgGroupList.map(gItem => gItem.exampleImg)
        this.exampleImgUrl = iItem.exampleImg
        uni.previewImage({
          current: iItem.exampleImg,
          urls: imgList,
          longPressActions: {
            itemList: ['保存图片'],
            success: function(data) {
              if (data.tapIndex === 0) {
                uni.saveImageToPhotosAlbum({
                  filePath: iItem.exampleImg,
                  success: (result) => {
                    uni.showToast({
                      title: '保存成功',
                      icon: 'none'
                    })
                  },
                  fail: (error) => {
                    uni.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            }
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/uni.scss';
  .form-content {
    border-radius: 16rpx;
    .title {
      display: flex;
      justify-content: space-between;
      padding: 0 30rpx 0 20rpx;
      border-bottom: 2rpx solid #E0E0E0;
    }
    .form-title { 
      display: flex; 
      align-items: center; 
      padding: 30rpx 0;
      font-size: 32rpx; 
      font-weight: bold; 
      color: #333333;
    }
    .picker-content {
      position: relative;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      // padding-right: 42rpx;
      text-align: right;
    }
    .tree-place {
      font-size: 28rpx;
      color: rgba(106, 106, 106, .5);
    }
    .tree-icon {
      margin: 0 4rpx 0 6rpx;
    }
  }
  .tree-item {
    display: flex;
    align-items: center;
    .placeholder {
      font-size: 28rpx;
      color: #ccc;
    }
  }
  .item-right-slot {
    padding-left: 10rpx !important;
    color: #999;
  }
  .example-img {
    width: 90%;
    height: auto;
    margin: auto;
  }
  .label-desc {
    font-size: 24rpx;
    color: #999;
  }
</style>
